import React from 'react';
import { connect } from 'dva';
import {
  WingBlank, WhiteSpace,
  List, InputItem, Button, Toast,
} from 'antd-mobile';
import { createForm } from 'rc-form';

const UpdatePasswordPage = ({ dispatch, form, ...rest }) => {
  const { getFieldProps, getFieldValue, getFieldError, validateFields } = form;
  const update = () => validateFields((errors, value) => {
    if (errors) {
      const fieldNames = Object.keys(errors);
      if (fieldNames[0]) {
        return Toast.fail(getFieldError(fieldNames[0]));
      }
    }

    dispatch({
      type: 'profile/updatePassword',
      payload: value,
    });
  });

  const checkConfirm = (rule, value, callback) => {
    if (value && getFieldValue('newPwd')) {
      validateFields(['repeatPwd']);
    }

    callback();
  };

  const checkPassword = (rule, value, callback) => {
    if (value && value !== getFieldValue('newPwd')) {
      Toast.fail('两次密码输入不相符，请重新输入');
    } else {
      callback();
    }
  };

  return (
    <WingBlank size="md">
      <WhiteSpace />
      <InputItem
        {...getFieldProps('pwd', {
          validate: [{
            trigger: false,
            rules: [{
              required: true,
              message: '请输入原始密码',
            }],
          }],
        })}
        placeholder="请输入原始密码" />
      <WhiteSpace />
      <List>
        <InputItem
          {...getFieldProps('newPwd', {
            validate: [{
              trigger: false,
              rules: [{
                required: true,
                message: '请输入新密码',
              }, {
                validator: checkConfirm,
              }]
            }],
          })}
          placeholder="请输入新密码" />
        <InputItem
          {...getFieldProps('repeatPwd', {
            validate: [{
              trigger: false,
              rules: [{
                required: true,
                message: '请确认新密码',
              }, {
                validator: checkPassword,
              }],
            }],
          })}
          placeholder="请确认新密码" />
      </List>
      <WhiteSpace size="xl" />
      <Button type="primary" onClick={update}>确认</Button>
    </WingBlank>
  );
};

export default connect()(createForm()(UpdatePasswordPage));
